from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.serializers import serialize
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from article.models import Article
from article.serializers import ArticleSerializer, DetailArticleSerializer
from my.models import User


# Create your views here.

class InfoView(APIView):
    # 获取
    def get(self, request, id):
        try:
            article_info = Article.objects.get(id=id)
        except Article.DoesNotExist:
            return Response({'code': 0, 'msg': "获取文章失败！", 'data': None})

        serializer = DetailArticleSerializer(article_info)
        return Response({'code':0, 'msg':"获取文章成功！", 'data':serializer.data})

    # 更新
    def put(self, request, id):
        article = Article.objects.filter(id=id).first()
        if not article:
            return Response({'code': 1, 'msg': "文章不存在", 'data': None})
        if article.user_id.id != request.user.id:
            return Response({'code': 1, 'msg': "没有修改权限", 'data': None})

        serializer = ArticleSerializer(article, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({'code':0, 'msg':"修改文章成功!", 'data':None})
        return Response({'code':1, 'msg':str(serializer.errors), 'data':None})

    def delete(self, request, id):
        article = Article.objects.filter(id=id).first()
        if not article:
            return Response({'code': 1, 'msg': "文章不存在", 'data': None})

        if article.user_id.id == request.user.id:
            article.delete()
            return Response({'code': 0, 'msg': '删除成功', 'data': None})

        return Response({'code': 1, 'msg': "没有删除权限", 'data': None})


class AddView(APIView):
    # 增加
    def post(self, request):
        data = request.data
        data['user_id'] = request.data.get('user_id')
        serializer = ArticleSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response({'code': 0, 'msg': "发布文章成功！", 'data': serializer.data})
        return Response({'code': 1, 'msg': serializer.errors, 'data': data})


class ListView(APIView):
    # 获取
    def get(self, request):
        articles = Article.objects.all().order_by('-id')

        state = request.GET.get('state')
        if state:
            articles = articles.filter(state=state)

        cate_id = request.GET.get('cate_id')
        if cate_id:
            articles = articles.filter(cate_id=cate_id)

        total = articles.count()

        page_num = request.GET.get('pagenum')
        page_size = request.GET.get('pagesize')

        try:
            page_num = int(page_num)
        except (ValueError, TypeError):
            page_num = 1

        try:
            page_size = int(page_size)
        except (ValueError, TypeError):
            page_size = 5

        paginator = Paginator(articles, page_size)
        try:
            articles = paginator.page(page_num)
        except EmptyPage:
            return Response({'code': 1, 'msg': "页码超出范围", 'data': None})

        # 序列化
        serializer = ArticleSerializer(articles, many=True)
        return Response({'code':0, 'msg':"获取文章列表成功！", 'data': {
                'list': serializer.data,  # 文章列表
                'total': total            # 总数量
            }
        })